Communication Patterns in Angular
How data flows in Angular
Angular follows a two-way data flow pattern, meaning you can send data up and down the component tree. As everything in the Angular is a component, understanding communication between components is crucial for every successful Angular project.
In this post, I will cover all the ways we can communicate between components. These are the topics we will go through:
- Example Project
- Component Basics
- Parent to Child Communication
- Child to Parent Communication
- Sibling Communication With Services
- Sibling Communication With EventEmitter
- Communication Using @ViewChild Decorator
- Communication Using Content Projection
- Communication With NGRX Store
- Communication Between Modules
- Summary
- Conclusion
Example Project
Here is the example project, so you can see all the communication in action. You can clone this project to test it on your machine.
// clone the project
git clone https://github.com/bbachi/angular-communication.git
// install all the dependencies and start the project
npm install
npm start
Component basics
I want to go over the basics of components, before diving into the communications between them. If you are already familiar with these concepts you can jump to the next section.
Angular follows component design pattern, which means that in Angular everything is a component. Your entire application is divided into modules and each module can be divided into small, reusable components. If you look at the diagram below, we have defined three modules and each module has a number of components. This module system helps load the app faster as only the necessary modules are loaded in the browser.
Usually we have components inside components to form the larger component, called composition. In the following diagram we have header, footer and dashboard components inside theapp component which forms the app module.
Module
Every component should be declared in the module by importing and place that in the declarations array of the module, as shown below: